package com.tuo51.bytedance.miniapp.service.impl;

import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSONObject;
import com.tuo51.bytedance.miniapp.service.BDRemoteCallService;
import com.tuo51.bytedance.utils.HttpClientUtil;
import com.tuo51.bytedance.vo.BDCode2SessionRequest;
import com.tuo51.bytedance.vo.BDCode2SessionResponseData;
import com.tuo51.bytedance.vo.BDResponse;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Service
public class BDRemoteCallServiceImpl implements BDRemoteCallService {

    private static String BYTEDANCE_OPEN_HOST = "https://developer.toutiao.com";

    private static String CODE2SESSION_API = BYTEDANCE_OPEN_HOST + "/api/apps/v2/jscode2session";

    public BDCode2SessionResponseData requestSession2Code(BDCode2SessionRequest request){

        String result = HttpClientUtil.sendPostJson(CODE2SESSION_API, request);

        if (StringUtils.isBlank(result)) {
            throw new BusinessException(ErrorCode.JSON_STR_ERROR, "请求接口失败");
        }

        BDResponse response = JSON.parseObject(result, BDResponse.class);

        if (response == null){
            throw new BusinessException(ErrorCode.JSON_STR_ERROR, "请求接口失败");
        }

        if (response.getErr_no() != 0){
            String msg = "授权失败";
            if (StringUtils.isNotBlank(response.getErr_tips())){
                msg = msg + " >远端: " + response.getErr_no() + " - " + response.getErr_tips();
            }
            throw new BusinessException(ErrorCode.PARAM_CAN_NOT_BLANK, msg);
        }

        Object o = response.getData();

        if (o instanceof JSONObject){
            JSONObject jo = (JSONObject) o;
            BDCode2SessionResponseData  data = jo.toJavaObject(BDCode2SessionResponseData.class);

            return data;
        }

        return null;
    }

}
